package org.moonlight.jvm.classfile.attribute.debuginfo;

import lombok.Getter;
import org.moonlight.jvm.classfile.ClassReader;
import org.moonlight.jvm.classfile.attribute.AttributeInfo;

/**
 * LocalVariableTypeTable 属于调试信息，以获取在方法运行时泛型局部变量的信息。在一个Code Attribute中只包含 1 或 0 项 LocalVariableTypeTable Attribute
 * 其结构定义如下:
 *   LocalVariableTypeTable_attribute {
 *     u2 attribute_name_index;
 *     u4 attribute_length;
 *     u2 local_variable_type_table_length;
 *     {
 *         u2 start_pc;
 *         u2 length;
 *         u2 name_index;
 *         u2 signature_index;
 *         u2 index;
 *     } local_variable_type_table[local_variable_type_table_length];
 *   }
 *
 * @author Moonlight
 * @createTime 2023/8/15 17:26
 **/
@Getter
public class LocalVariableTypeTableAttribute implements AttributeInfo {

    private LocalVariableTypeTableEntry[] localVariableTypeTable;

    @Override
    public void readInfo(ClassReader reader) {
        int localVarTableTypeLength = reader.readUint16();
        LocalVariableTypeTableEntry[] localVariableTypeTable = new LocalVariableTypeTableEntry[localVarTableTypeLength];
        for (int i = 0; i < localVarTableTypeLength; i++) {
            localVariableTypeTable[i] = new LocalVariableTypeTableEntry(
                    reader.readUint16(), reader.readUint16(), reader.readUint16(), reader.readUint16(), reader.readUint16()
            );
        }
        this.localVariableTypeTable = localVariableTypeTable;
    }

    @Getter
    static class LocalVariableTypeTableEntry {
        private final int startPc;
        private final int length;
        private final int nameIdx;
        private final int signatureIdx;
        private final int idx;

        LocalVariableTypeTableEntry(int startPc, int length, int nameIdx, int signatureIdx, int idx) {
            this.startPc = startPc;
            this.length = length;
            this.nameIdx = nameIdx;
            this.signatureIdx = signatureIdx;
            this.idx = idx;
        }
    }

}
